package com.ruoyi.web.controller.frequencyPoint;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;

//import jcifs.smb.NtlmPasswordAuthentication;
//import jcifs.smb.SmbFile;
import org.apache.tomcat.jni.FileInfo;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.file.AccessDeniedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author ASUS
 * @Date 2025-7-9 23:01
 * @describe
 */
@RestController
@RequestMapping("/frequencyPoint")
public class FrequencyPointController extends BaseController {

    @Value("${thirdPlatform.path}")
    private String thirdPlatformPath;


    public String getFilePath(String PinDian, String studentName) {
        String path;
        String param = "PinDian=" + PinDian + "&" + "studentName=" + studentName;
        String s = HttpUtils.sendGet(thirdPlatformPath, param);
        JSONObject jsonObject = JSONObject.parseObject(s);
        if (jsonObject != null) {
            if (jsonObject.containsKey("state") && jsonObject.getIntValue("state") == 1) {
                path = jsonObject.getString("info");
                System.out.println("111111111111111111111111====="+path);
                return path;
            }
        }
        return null;
    }

    @GetMapping("/getFileNmae")
    public Map<String, String> getFileNmae(@RequestParam("PinDian") String PinDian) throws IOException {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        String studentName = user.getNickName();
        String filePath =  getFilePath(PinDian, studentName);
        filePath = filePath.replaceAll("XDPath","mnt/win_share");
        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
        Map<String, String> result = new HashMap<>();
        result.put("filePath", filePath);
        result.put("fileName", fileName);
        return result;
    }

    @PostMapping("/fileDownload1")
    public void downloadFile(@RequestBody Map<String, String> params,
                             HttpServletResponse response) throws IOException {
        String filePath = params.get("filePath");
        String fileName = params.get("fileName");
        System.out.println("filePath=============="+filePath);
        System.out.println("fileName=============="+fileName);
        File file = new File(filePath);
        if (!file.exists()) {
            throw new RuntimeException("文件不存在");
        }

        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

        try (InputStream in = new FileInputStream(file);
             OutputStream out = response.getOutputStream()) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
        }
    }






    @PostMapping("/fileDownload")
    public ResponseEntity<InputStreamResource> fileDownload(@RequestBody Map<String, String> params) throws IOException {
        String filePath = params.get("filePath");
        String fileName = params.get("fileName");
        //System.out.println("filePath=============="+filePath);
        System.out.println("fileName=============="+fileName);
        //filePath = "D:\\22.rar";
        FileInputStream fileInputStream = new FileInputStream(filePath);

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename="+fileName)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(new InputStreamResource(fileInputStream));
    }


    public static List<WaveformSample> getDataForPage(List<WaveformSample> dataList, int page, int pageSize) {

        int fromIndex = (page - 1) * pageSize;
        int toIndex = Math.min(page * pageSize, dataList.size()); // 确保不越界
        System.out.println("fromIndex = " + fromIndex + "   toIndex = " + toIndex);
        if (fromIndex >= dataList.size() || fromIndex < 0) {
            return new ArrayList<>();
        }
        return dataList.subList(fromIndex, toIndex);
    }

    private static List<WaveformSample> samples = null;
    @GetMapping("/waveformParse")
    public AjaxResult parsePcmFile(@RequestParam("dataCount") Integer dataCount, @RequestParam("PinDian") String PinDian) throws IOException {
        try {
            SysUser user = SecurityUtils.getLoginUser().getUser();
            String studentName = user.getUserName();
            List<WaveformSample> sampleList = null;
            if (CollectionUtils.isEmpty(samples)) {
                String filePath = "";
                String endPath = "";
                if (StringUtils.isEmpty(filePath)) {
                    //正式
                    filePath = getFilePath(PinDian, studentName);
                    filePath = filePath.replaceAll("XDPath","mnt/win_share");
                    //测试
                   // filePath = "D:\\LD_4MFS_500Kbaud_qpsk.pcm";
                    System.out.println("endPath============"+filePath);
                    if (StringUtils.isEmpty(filePath)) {
                        return AjaxResult.error("调用三方接口异常！");
                    }
                }
                double sampleRate = Double.parseDouble(PinDian.replaceAll("(?i)\\s*mhz\\s*", ""));
                samples = parsePcmFile(filePath, sampleRate*1e6);
                sampleList = getDataForPage(samples, dataCount, 2000);
            } else {
                sampleList = getDataForPage(samples, dataCount, 2000);
            }
            return AjaxResult.success(sampleList);
        } catch (IOException e) {
            System.err.println("文件处理错误: " + e.getMessage());
            e.printStackTrace();
        }
        return AjaxResult.success(null);
    }

    // 配置参数（根据实际情况调整）
    private static final double SAMPLE_RATE = 2.0e6; // 采样率2MHz（需根据实际文件调整）
    private static final int BIT_DEPTH = 16;        // 16位有符号整数
    private static final ByteOrder BYTE_ORDER = ByteOrder.BIG_ENDIAN;
    private static final double DISPLAY_DURATION = 0.01; // 显示10ms的数据
    private static final int Y_MIN = -3000;         // 纵轴最小值
    private static final int Y_MAX = 3000;          // 纵轴最大值

    public static void main(String[] args) {
        String filePath = "E:\\LD_4MFS_500Kbaud_qpsk(1).pcm";

        try {
            // 1. 读取并解析PCM文件
            List<WaveformSample> samples = parsePcmFile(filePath, SAMPLE_RATE);

            // 2. 绘制波形图
            plotWaveforms(samples);

        } catch (IOException e) {
            System.err.println("文件处理错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 解析PCM文件
     * @return
     */
    private static List<WaveformSample> parsePcmFile(String filePath, double sampleRate) throws IOException {
        File file = new File(filePath);
        long fileSize = file.length();
        int bytesPerSample = BIT_DEPTH / 8;
        int totalSamples = (int)(fileSize / bytesPerSample);

        // 读取文件内容到字节数组
        byte[] fileData = new byte[(int)fileSize];
        try (FileInputStream fis = new FileInputStream(file)) {
            fis.read(fileData);
        }

        // 转换为short数组
        ByteBuffer buffer = ByteBuffer.wrap(fileData).order(BYTE_ORDER);
        short[] shortData = new short[totalSamples];
        buffer.asShortBuffer().get(shortData);

        // 创建采样列表
        List<WaveformSample> samples = new ArrayList<>();
        for (int i = 0; i < shortData.length; i++) {
            double timeInSeconds = i / sampleRate;
            samples.add(new FrequencyPointController.WaveformSample(timeInSeconds * 1000, shortData[i]));
        }

        return samples;
    }

    /**
     * 绘制波形图
     */
    private static void plotWaveforms(List<WaveformSample> samples) {
        // 创建数据集
        XYSeries waveformSeries = new XYSeries("PCM Waveform");

        // 计算显示间隔（优化性能）
        int totalPointsToShow = (int)(DISPLAY_DURATION * SAMPLE_RATE);
        int step = Math.max(1, samples.size() / totalPointsToShow);

        // 添加数据点（只显示指定时间范围内的数据）
        for (int i = 0; i < samples.size() && samples.get(i).time <= DISPLAY_DURATION; i += step) {
            FrequencyPointController.WaveformSample sample = samples.get(i);
            waveformSeries.add(sample.time * 1000, sample.value); // 时间转换为毫秒
        }

        // 创建图表
        XYSeriesCollection dataset = new XYSeriesCollection();
        dataset.addSeries(waveformSeries);

        JFreeChart chart = ChartFactory.createXYLineChart(
                "PCM Waveform (" + (SAMPLE_RATE/1e6) + " MHz Sample Rate)",
                "Time (ms)",
                "Amplitude",
                dataset
        );

        // 设置Y轴范围
        XYPlot plot = chart.getXYPlot();
        NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
//        rangeAxis.setRange(Y_MIN, Y_MAX);

        // 显示图表窗口
        ChartFrame frame = new ChartFrame("PCM波形分析", chart);
        frame.pack();
        frame.setVisible(true);
    }

    /**
     * 波形采样数据容器
     */
    static class WaveformSample {
        final double time;  // 时间（秒）
        final int value;    // 采样值（原始int16值）

        WaveformSample(double time, int value) {
            this.time = time;
            this.value = value;
        }

        public double getTime() {
            return time;
        }

        public int getValue() {
            return value;
        }
    }

//    public static List<WaveformSample> getDataForPage(List<WaveformSample> dataList, int page, int pageSize) {
//
//        int fromIndex = (page - 1) * pageSize;
//        int toIndex = Math.min(page * pageSize, dataList.size()); // 确保不越界
//        System.out.println("fromIndex = " + fromIndex + "   toIndex = " + toIndex);
//        if (fromIndex >= dataList.size() || fromIndex < 0) {
//            return new ArrayList<>();
//        }
//        return dataList.subList(fromIndex, toIndex);
//    }

}
